//服务器地址
let config = require("../config/config.js");
const host = config.request_url;

/**
 * 封装wx.request请求
 * @param {String} url 请求接口地址
 * @param {String} method 请求方式
 * @param {Object} data 请求参数
 * @param {Number} headerType 请求头类型
 * @param {Boolean} isLoading 是否显示loading
 */
function http(
  url,
  method,
  data,
  headerType,
  isLoading,
  timeout,
  maxRetryTimes = 3
) {
  let retryTimes = 0;
  let header = { "content-type": "application/x-www-form-urlencoded" };
  const _timeout = timeout ? timeout : 20000;
  if (typeof headerType === "boolean") {
    isLoading = headerType;
    headerType = null;
  }
  if (typeof data !== "object") {
    headerType = data;
    data = {};
    isLoading = headerType;
  }
  if (headerType === 0) {
    header["content-type"] = "application/json";
  }
  if (headerType === 1) {
    header["content-type"] = "application/x-www-form-urlencoded";
  }
  if (method === "GET") {
    header = {};
  }
  if (wx.getStorageSync("token")) {
    header.token = wx.getStorageSync("token");
  }
  if (isLoading !== false) {
    wx.showLoading({ title: "加载中..." });
  } else {
    wx.hideLoading();
  }
  return new Promise((resolve, reject) => {
    const doRequest = () => {
      const task = wx.request({
        method: method,
        url: host + url,
        data: data,
        header: header,
        timeout: _timeout,
        success: (res) => {
          if (res.data.code == 401) {
            wx.clearStorageSync();
            wx.reLaunch({ url: "/pages/login/login" });
          }
          if (isLoading !== false) {
            wx.hideLoading();
          }
          if (res.data.code && res.data.code != 200) {
            wx.showToast({
              title: res.data.desc,
              icon: "none",
              duration: 3000,
            });
            reject(res);
            return;
          }
          resolve(res);
        },
        fail: (err) => {
          if (isLoading !== false) {
            wx.hideLoading();
          }
          if (err.errMsg == "request:fail timeout") {
            wx.showToast({
              title: "您的网络不给力，请稍后重试",
              icon: "none",
              duration: 3000,
            });
            task.abort(); // 终止请求
            reject(err); // 结束 Promise
            return;
          }
          retryTimes++;
          if (retryTimes < maxRetryTimes) {
            doRequest();
          } else {
            reject(err);
          }
        },
      });
    };
    doRequest();
  });
}

// 导出http方法
module.exports = {
  http,
};
